/*
 * @lc app=leetcode.cn id=1963 lang=cpp
 *
 * [1963] 使字符串平衡的最小交换次数
 */

// @lc code=start
class Solution
{
public:
    int minSwaps(string s)
    {
        int n = s.size();
        int ans = 0, l = 0, r = n - 1, lcnt, rcnt;
        lcnt = s[l] == '[' ? 1 : -1;
        rcnt = s[r] == ']' ? 1 : -1;
        while (l < r)
        {
            while (l < r && lcnt >= 0)
            {
                lcnt += s[++l] == '[' ? 1 : -1;
            }
            while (l < r && rcnt >= 0)
            {
                rcnt += s[--r] == ']' ? 1 : -1;
            }
            if (l >= r)
            {
                break;
            }
            ans++;
            lcnt += 2, rcnt += 2;
        }
        return ans;
    }
};
// @lc code=end
